package cn.demarcia.coco.ui.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.demarcia.coco.R;
import cn.demarcia.coco.ui.adapter.WeekWeatherAdapter;
import cn.demarcia.coco.uihelper.StringUtils;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import info.jimao.newsdk.JuHeApi;
import info.jimao.newsdk.callbacks.SingleDataCallback;
import info.jimao.newsdk.models.WeatherDataModel;
import info.jimao.newsdk.models.WeatherModel;
import info.jimao.newsdk.results.SingleDataResult;
import okhttp3.Call;

/**
 * Created by lzy
 * on 2016/8/8.
 */
public class WeatherActivity extends BaseActivity implements BDLocationListener {
    public LocationClient locationClient = null;
    private String cityName;
    private WeatherDataModel weatherDataModel;
    private LinearLayoutManager layoutManager;
    private RecyclerView.Adapter adapter;


    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.tvCity)
    TextView tvCity;                    //顶部地址名
    @Bind(R.id.tvTemperature)
    TextView tvTemperature;             //顶部温度
    @Bind(R.id.tvWindDirect)
    TextView tvWindDirect;              //风向
    @Bind(R.id.tvWindPower)
    TextView tvWindPower;               //风力
    @Bind(R.id.tvHumidityInfo)
    TextView tvHumidity;                //湿度
    @Bind(R.id.tvWeatherInfo)
    TextView tvWeatherInfo;            //天气信息
    @Bind(R.id.tvUpdateTime)
    TextView tvUpdateTime;              //更新时间
    @Bind(R.id.tvSuggestSport)
    TextView tvSport;                   //运动指数
    @Bind(R.id.tvSuggestCarWash)
    TextView tvCarWash;                //洗车指数
    @Bind(R.id.tvSuggestDress)
    TextView tvDress;                   //穿衣指数
    @Bind(R.id.tvSuggestUl)
    TextView tvUl;                       //紫外线指数
    @Bind(R.id.tvSunriseTime)
    TextView tvSunriseTime;             //日出时间
    @Bind(R.id.tvSunsetTime)
    TextView tvSunsetTime;              //日落时间
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;          //一周天气视图

    private List<Object> items = new ArrayList<>();//一周天气情况

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationClient = new LocationClient(getApplicationContext());
        locationClient.registerLocationListener(this);

        setContentView(R.layout.activity_weather);
        ButterKnife.bind(this);
        setSupportActionBar(toolbar);
        //noinspection deprecation
        toolbar.setTitleTextColor(getResources().getColor(R.color.white));
        toolbar.setNavigationIcon(R.drawable.ic_add_city);

        adapter = new WeekWeatherAdapter(this, items);
        layoutManager = new GridLayoutManager(this, 6);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);

        initLocation();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //初始化定位信息
    private void initLocation() {
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setIsNeedAddress(true);
        option.setIgnoreKillProcess(false);     //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        locationClient.setLocOption(option);
        locationClient.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        locationClient.stop();
    }

    //定位服务监听
    @Override
    public void onReceiveLocation(BDLocation bdLocation) {
        cityName = bdLocation.getCity();
        toolbar.setTitle(bdLocation.getCity());
        if (!StringUtils.isEmpty(bdLocation.getDistrict())) {
            tvCity.setText(bdLocation.getDistrict());
        } else {
            tvCity.setText(bdLocation.getCity());
        }
        getWeatherData(cityName);
    }

    //获取天气数据
    private void getWeatherData(String cityName) {
        JuHeApi weatherApi = new JuHeApi(this);
        weatherApi.getWeather(cityName, new SingleDataCallback<WeatherModel>(WeatherModel.class) {
            @Override
            public void onError(Call call, Exception e) {
                super.onError(call, e);
            }

            @Override
            public void onResponse(SingleDataResult<WeatherModel> response) {
                super.onResponse(response);
                if (response.getResult() != null) {
                    weatherDataModel = response.getResult().data;
                    items.addAll(response.getResult().data.getWeather());
                    adapter.notifyDataSetChanged();

                    refreshView();
                }
            }
        });
    }

    //获取天气数据后，加载天气信息
    private void refreshView() {
        tvTemperature.setText(getString(R.string.weather_unit, weatherDataModel.getRealtime().getWeather().getTemperature()));
        tvWindPower.setText(weatherDataModel.getRealtime().getWind().getPower());
        tvWindDirect.setText(weatherDataModel.getRealtime().getWind().getDirect());
        tvHumidity.setText(getString(R.string.percent, weatherDataModel.getRealtime().getWeather().getHumidity()));
        tvWeatherInfo.setText(weatherDataModel.getRealtime().getWeather().getInfo());
        tvUpdateTime.setText(getString(R.string.weather_update_time, weatherDataModel.getRealtime().getDate(), weatherDataModel.getRealtime().getTime()));
        tvSport.setText(weatherDataModel.getLife().getInfo().getYundong().get(0));
        tvCarWash.setText(weatherDataModel.getLife().getInfo().getXiche().get(0));
        tvDress.setText(weatherDataModel.getLife().getInfo().getChuanyi().get(0));
        tvUl.setText(weatherDataModel.getLife().getInfo().getZiwaixian().get(0));
        tvSunriseTime.setText(weatherDataModel.getWeather().get(0).getInfo().getDay().get(5));
        tvSunsetTime.setText(weatherDataModel.getWeather().get(0).getInfo().getNight().get(5));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_share) {
            showShare();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void showShare() {
        ShareSDK.initSDK(WeatherActivity.this);
        OnekeyShare oks = new OnekeyShare();
//关闭sso授权
        oks.disableSSOWhenAuthorize();
// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("CoCo");
// text是分享文本，所有平台都需要这个字段
        oks.setText("CoCo天气预报");
        oks.setViewToShare(getWindow().getDecorView());
// 启动分享GUI
        oks.show(this);
    }
}
